import json
from django import template
from django.contrib.auth.models import Group
from django.core.cache import cache

register = template.Library()


@register.simple_tag(takes_context=True)
def check_user_groups(context, group_str):
    groups = group_str.split(',')  # 按,分割成列表
    user = context['request'].user

    if user.is_superuser:
        return True

    cache_key = f"user_{user.id}_groups"
    user_groups = cache.get(cache_key)

    if not user_groups:
        user_groups = set(user.groups.values_list('name', flat=True))
        cache.set(cache_key, user_groups, 300)  # 缓存5分钟

    return not set(groups).isdisjoint(user_groups)

